﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OMS.OMSService;
using OMS.Models;
using PagedList;

namespace OMS.Controllers
{
    public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles="customer")]
        public ActionResult Ordering(string condition, string field, string pattern, int? page)
        {
            ViewBag.Condition = condition;
            ViewBag.Field = field;
            ViewBag.Pattern = pattern;
            int userId = Int32.Parse(Request.Cookies["UserId"].Value);
            Service1 service = new Service1();
            UserModel userModel = new UserModel();
            List<OrderModel> orderModels = new List<OrderModel>();
            List<OrderModelView> orderModelViews = new List<OrderModelView>();
            orderModels = service.GetOrdersByCustomer(userId, true).ToList();
            if (!String.IsNullOrEmpty(pattern))
            {
                switch(field)
                {
                    case "ordername":
                        orderModels = orderModels.Where(m => m.OrderNumber.StartsWith(pattern)).ToList();
                        break;
                    case "status": 
                        orderModels = orderModels.Where(m => m.Status.StartsWith(pattern)).ToList();
                        break;
                }
                orderModels = orderModels.Where(m => m.Status.Equals(condition)).ToList();
            }

            
            foreach (var order in orderModels)
            {
                orderModelViews.Add(new OrderModelView(order));
                foreach (var orderModel in orderModels)
                    if (orderModelViews.Last().Asignee > 0)
                    {
                        userModel = service.GetUserById(orderModelViews.Last().Asignee, true);
                        orderModelViews.Last().AsigneeName = userModel.FirstName + ' ' + userModel.LastName;
                    }
            }
            int pageSize = 10;
            int pageNumber = (page ?? 1);
            return View(orderModelViews.ToPagedList(pageNumber, pageSize));
        }

        [Authorize(Roles = "customer")]
        public ActionResult AddOrder()
        {
            FullOrderModelView orderModelView = new FullOrderModelView();
            orderModelView.Order.DateOfOrdering = DateTime.Now.Date;
            orderModelView.Order.DeliveryDate = DateTime.Now.Date;
            orderModelView.Order.Status = "created";
            List<SelectListItem> merchList = GetMerches();
            ViewBag.Merches = merchList;
            return View(orderModelView);
        }

        #region Helper

        private static List<SelectListItem> GetMerches()
        {
            Service1 service = new Service1();
            var query = service.FilterUsers("role", "equal", "merch");
            List<SelectListItem> merchList = new List<SelectListItem>();
            merchList.Add(new SelectListItem
            {
                Value = "0",
                Text = "Administrator"
            });
            foreach (var merch in query)
            {
                merchList.Add(new SelectListItem
                {
                    Value = merch.Id.ToString(),
                    Text = merch.FirstName + ' ' + merch.LastName,
                });
            }
            return merchList;
        }

        #endregion

        [Authorize(Roles = "customer")]
        [HttpPost]
        public ActionResult AddOrder(FullOrderModelView orderModelView)
        {
            int resId = -1;
            bool idSpec = false;
            if (ModelState.IsValid)
            {
                bool createRes = false, createResSpec = false;
                OrderModel orderModel = orderModelView.GetOrderModel();
                orderModel.CustomerId = Int32.Parse(Request.Cookies["UserId"].Value);
                Service1 service = new Service1();
                service.CreateOrder(orderModel, out resId, out idSpec);
            }
            if (resId != -1)
                return RedirectToAction("EditOrder", new { orderId = resId });
            else
                return RedirectToAction("AddOrder");// View(orderModelView);
        }

        [Authorize(Roles = "customer")]
        public ActionResult EditOrder(int orderId)
        {
            Service1 service = new Service1();
            OrderModelView orderModelView = new OrderModelView(service.GetOrderById(orderId,true));
            CreditCardModelView creditCardModelView = new CreditCardModelView(service.GetCardByOrderId(orderModelView.Id, true));
            FullOrderModelView fullView = new FullOrderModelView(orderModelView, creditCardModelView);
            List<SelectListItem> merchList = GetMerches();
            ViewBag.Merches = merchList;
            if (orderModelView.Asignee > 0)
            {
                ViewBag.SelectedMerch = Int32.Parse(merchList.Find(m => m.Value == orderModelView.Asignee.ToString()).Value);
            }
            else
            {
                ViewBag.SelectedMerch = 0;
            }
            
            return View(fullView);
        }

        [Authorize(Roles = "customer")]
        [HttpPost]
        public ActionResult EditOrder(FullOrderModelView fullOMV, string submitButton)
        {
            Service1 service = new Service1();
            OrderModel orderModel = service.GetOrderById(fullOMV.Order.Id, true);
            CreditCardModel creditCard = fullOMV.GetCreditCard();
            orderModel.Card = creditCard;
            orderModel.PrefDeliveryDate = fullOMV.Order.PrefDate;
            orderModel.PrefDeliveryDateSpecified = true;
            orderModel.MerchId = fullOMV.Order.Asignee;
            orderModel.MerchIdSpecified = true;
            orderModel.OrderNumber = fullOMV.Order.OrderNumber;
            bool res=false, resSpec=false;
            if (submitButton == "order")
            {
                orderModel.Status = "ordered";
            }
            service.EditOrder(orderModel, out res, out resSpec);
            if (res)
                return RedirectToAction("Ordering");
            else
                return RedirectToAction("/Error");
        }


        [Authorize(Roles = "customer")]
        public ActionResult DeleteOrder(int orderId)
        {
            return View();
        }

        //[Authorize(Roles = "customer")]
        //[HttpPost]
        //public ActionResult DeleteOrder(int orderId)
        //{
        //    Service1 service = new Service1();
        //    bool res = false, resSpec = false;
        //    service.DeleteOrder(orderId, true, out res, out resSpec);
        //    if (res)
        //        return RedirectToAction("Ordering");
        //    else
        //        return RedirectToAction("/Error");
        //}

        [Authorize(Roles = "customer")]
        public ActionResult AddItem(int orderId, string filterBy, string searchString, int? page)
        {
            ViewBag.OrderId = orderId;
            ViewBag.FilterBy = filterBy;
            ViewBag.SearchString = searchString;
            List<ItemModelView> itemModelViews = new List<ItemModelView>();
            List<ItemModel> itemModels = new List<ItemModel>();
            Service1 service = new Service1();
            if (!String.IsNullOrEmpty(searchString))
            {
                switch (filterBy)
                {
                    case "name":
                        itemModels = service.FilterByName(searchString).ToList();
                        break;
                    case "description":
                        itemModels = service.FilterByDescription(searchString).ToList();
                        break;
                }
            }
            else
            {
                itemModels = service.GetAllItems().ToList();
            }
            foreach (ItemModel itemModel in itemModels)
            {
                itemModelViews.Add(new ItemModelView(itemModel));
            }
            ViewBag.OrderId = orderId;
            int pageSize = 10;
            int pageNumber = (page ?? 1);
            return View(itemModelViews.ToPagedList(pageNumber, pageSize));
        }

        [Authorize(Roles = "customer")]
        [HttpPost]
        public ActionResult AddItem(FormCollection formCollection, int orderId)
        {
            int itemId = -1, quantity = -1;
            Int32.TryParse(formCollection["item_id"],out itemId);
            Int32.TryParse(formCollection["quantity"], out quantity);
            string dimension = formCollection["dimension"];
            OrderItemModel orderItemModel = new OrderItemModel
            {
                ItemId = itemId,
                ItemIdSpecified = true,
                Quantity = quantity,
                QuantitySpecified = true,
                Dimension = dimension
            };
            bool addRes = false, addResSpec = false;
            Service1 service = new Service1();
            service.AddOrderItemToOrder(orderId, true, orderItemModel, out addRes, out addResSpec);
            if(addRes)
                return RedirectToAction("EditOrder", new { orderId });
            else
                return RedirectToAction("EditOrder", new { orderId });//TODO: RedirectToArror
        }

        [Authorize(Roles = "customer")]
        public ActionResult EditItem(int orderItemId, int orderId)
        {
            ViewBag.OrderId = orderId;
            Service1 service = new Service1();
            OrderItemModel orderItem = service.GetOrderItemById(orderItemId,true);
            OrderItemModelView orderItemModelView = new OrderItemModelView(orderItem);
            return View(orderItemModelView);
        }


        [Authorize(Roles = "customer")]
        [HttpPost]
        public ActionResult EditItem(OrderItemModelView orderItemMV, int orderId)
        {
            Service1 service = new Service1();
            OrderItemModel orderItemModel = service.GetOrderItemById(orderItemMV.Id, true);
            orderItemModel.Quantity = orderItemMV.Quantity;
            orderItemModel.Dimension = orderItemMV.Dimension;
            bool editRes = false, editResSpec = false;
            service.EditOrderItem(orderItemModel, out editRes, out editResSpec);
            if (editRes)
                return RedirectToAction("EditOrder", new { orderId });
            else
                return RedirectToAction("/Error");
        }

        [Authorize(Roles = "customer")]
        public ActionResult DeleteItem(int orderItemId, int orderId)
        {
            ViewBag.OrderId = orderId;
            Service1 service = new Service1();
            OrderItemModel orderItem = service.GetOrderItemById(orderItemId, true);
            OrderItemModelView orderItemModelView = new OrderItemModelView(orderItem);
            return View(orderItemModelView);
        }

        [Authorize(Roles = "customer")]
        [HttpPost]
        public ActionResult DeleteItem(FormCollection formCollection)
        {
            int orderId = Int32.Parse(formCollection["orderId"]);
            int orderItemId = Int32.Parse(formCollection["orderItemId"]);
            Service1 service = new Service1();
            ViewBag.OrderId = orderId;
            bool delRes = false, resSpec = false;
            service.DeleteOrderItem(orderItemId, true, out delRes, out resSpec);
            if (delRes)
                return RedirectToAction("EditOrder", new { orderId });
            else
                return RedirectToAction("/Error");
        }

    }
}
